package com.dems.core.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/*import service.util.SslConnection;*/

public class HttpUtils {

	public static String doHttpPost(String url,Map<String,String> params) {
		// 1. 创建HttpClient对象
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		// 2. 创建HttpPost对象
		HttpPost post = new HttpPost(url);
		// 3. 设置POST请求传递参数
		Set<String> set = params.keySet();
		Iterator<String> iterator = set.iterator();
		List<NameValuePair> paramList = new ArrayList<NameValuePair>();
		while(iterator.hasNext()) {
			String key = iterator.next();
			String value = params.get(key);
			paramList.add(new BasicNameValuePair(key, value));
		}
		try {
		    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
		    post.setEntity(entity);
		} catch (UnsupportedEncodingException e) {
		    e.printStackTrace();
		}
		// 4. 执行请求并处理响应
		try {
		    CloseableHttpResponse response = httpClient.execute(post);
		    HttpEntity entity = response.getEntity();
		    if (entity != null){
		    	return EntityUtils.toString(entity);
		    }
		    response.close();
		} catch (ClientProtocolException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		} finally {
		    // 释放资源
		    try {
		        httpClient.close();
		    } catch (IOException e) {
		        e.printStackTrace();
		    }
		}
		return "";
	}

}
